<?php
/**
 * 自动取消订单
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/1/4
 * @copyright PanxSoft Inc.
 */
namespace App\Jobs;

use App\Http\Services\Api\V1\App\Product\OrderService;
use App\Models\Order\Order;
use App\Models\Order\OrderAutoSign;
use App\Models\Order\OrderStatus;
use App\Services\Utils\ApiChecker;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class AutoCancelOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels ,ApiChecker;

    /**
     * @var int
     */
    private $order_id;

    /**
     * Create a new job instance.
     *
     * @param Order $order
     */
    public function __construct(Order $order)
    {
        $this->order_id = $order->getKey();
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \Exception
     */
    public function handle()
    {
        /** @var Order $order */
        $order = (new Order)->find($this->order_id);
        if (! $this->validateAutoCancel($order)) {
            return;
        }

        (new OrderService)->deleteOrder($order);
    }

    /**
     * @param Order|null $order
     *
     * @return bool
     */
    private function validateAutoCancel(?Order $order): bool
    {
        if (! $order) {
            logger()->error("Order[ID:$this->order_id] not found!");
            return false;
        }

        if ($order->isOrderStatusUnpaid()) {
            logger()->error("Order[ID:$this->order_id] status[$order->order_status_id] not unpaid!");
            return false;
        }

        return true;
    }
}
